function [bestacc, bestc, bestg, cvmat] = svmcg3(lbl, inst, settings)
if isfield(settings, 'cbin')
    cbin = settings.cbin;
else
    cbin = -5:2:15;
end
if isfield(settings, 'gbin')
    gbin = settings.gbin;
else
    gbin = -15:2:3;
end
if isfield(settings, 'vfold')
    v = settings.vfold;
else
    v = 5;
end

ncbin = length(cbin);
ngbin = length(gbin);
vcbin = 2.^ cbin;
vgbin = 2.^ gbin;

cvmat = nan(ncbin, ngbin); %store results of all c,g
[cl,gl] = meshgrid(vcbin, vgbin);
ncl = numel(cl);
bestacc = -1;
bestc = NaN;
bestg = NaN;

if settings.verbose < 3
    settings.cg_opt = [settings.cg_opt,' -q'];
end
output = '';
for i = 1:ncl
    ind = 1;
    c = cl(i);
    g = gl(i);
    arg = [settings.cg_opt, ' -v ',num2str(v),' -c ', num2str(c), ' -g ', num2str(g)];
    acc = libsvmtrain_fv(lbl, inst, arg, settings, ind); %accuracy for cross validation
    cvmat(i) = acc;
    if acc > bestacc
        bestc = c;
        bestg = g;
        bestacc = acc;
    end
    if settings.verbose == 1
        fprintf(repmat('\b',1,length(output)));
    end
    output = sprintf('%d/%d : C = %g, G = %g acc = %g\n (best: c = %g, g = %g, acc = %g)', i, ncl, c, g, acc, bestc, bestg, bestacc);
    fprintf('%s',output);
    
    bmat = cvmat;
    bmat(isnan(bmat)) = 0;
    [C,h]=contourf(gbin, cbin, cvmat, 6);
    clabel(C,h);
    title(output);
    pause(0.05);

end
if settings.verbose == 1
    fprintf([repmat('\b',1,length(output)),'\n']);
end
output = '';

v_bestacc = max(cvmat(:));
ind = find(cvmat >= v_bestacc);
v_bestc = cl(ind(1));
v_bestg = gl(ind(1));
if settings.verbose == 3
    fprintf('%g=%g,%g=%g,%g=%g\n',v_bestacc, bestacc, v_bestc, bestc, v_bestg, bestg);
end
end